/*
 * @lc app=leetcode.cn id=450 lang=cpp
 *
 * [450] 删除二叉搜索树中的节点
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* getMin(TreeNode* root)
    {
        while(NULL != root->left)
        {
            root = root->left;
        }
        return root;
    }


    TreeNode* deleteNode(TreeNode* root, int key) {
        if(root == NULL)
            return NULL;
        
        if(root->val == key)
        {
            //处理第一种情况
            if(root->left == NULL)
                return root->right;
            //处理第二种情况
            if(root->right == NULL)
                return root->left;
            //处理第三种情况-两边均有节点,此处方案是将右节点中最小元素作为root节点
            TreeNode* minNode = getMin(root->right);
            root->val = minNode->val;
            root->right = deleteNode(root->right,minNode->val);
        }
        else if(root->val > key)
        {
            root->left = deleteNode(root->left,key);
        }   
        else if(root->val < key)
        {
            root->right = deleteNode(root->right,key);
        }
        return root;
    }

};
// @lc code=end

